﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using static Android.Widget.AdapterView;

namespace Medicine.Core.Listeners
{
    public class ListViewOnItemLongClickListener<T, F> : Java.Lang.Object, IOnItemLongClickListener
            where T : BaseAdapter<F>, new()
            where F : new()
    {
        private ListView sender;

        public ListViewOnItemLongClickListener(object sender)
             : base(JNIEnv.StartCreateInstance("mono/android/widget/AdapterView_OnItemLongClickListenerImplementor", "()V"), JniHandleOwnership.TransferLocalRef)
        {
            JNIEnv.FinishCreateInstance(base.Handle, "()V");
            this.sender = sender as ListView;
        }

        public bool OnItemLongClick(AdapterView parent, View view, int position, long id)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(view.Context);
            builder.SetMessage("确定删除?");
            builder.SetTitle("提示");

            builder.SetPositiveButton("确定", new EventHandler<DialogClickEventArgs>((s, e) =>
            {
                var adapter = (sender.Adapter as T);
                var removeData = adapter[position];
                if (removeData != null)
                {
                    var result = DbContext.DbC.Delete(removeData);
                    if (result > 0)
                    {
                        adapter.NotifyDataSetChanged();
                        Helpers.MessageShow.ShowShortMsg(sender.Context, "删除成功");
                    }
                    else
                        Helpers.MessageShow.ShowShortMsg(sender.Context, "删除失败");
                }
            }));

            builder.SetNegativeButton("取消", new EventHandler<DialogClickEventArgs>((s, e) =>
            {

            }));

            builder.Create().Show();
            return true;
        }
    }

}